#!/usr/bin/env bash

# wrapper for smaller output from __rvm_log_command
__rvm_rm_rf()
{
  __rvm_rm_rf_verbose "$@"
}
#
# \command \rm -rf with *some* safeguards in place.
#
__rvm_rm_rf_verbose()
{
  \typeset target
  target="${1%%+(/|.)}"

  #NOTE: RVM Requires extended globbing shell feature turned on.
  if
    [[ -n "${ZSH_VERSION:-}" ]]
  then
    \builtin setopt extendedglob
  elif
    [[ -n "${BASH_VERSION:-}" ]]
  then
    \builtin shopt -s extglob
  else
    rvm_error "What the heck kind of shell are you running here???"
  fi
  case "${target}" in
    (*(/|.)@(|/Applications|/Developer|/Guides|/Information|/Library|/Network|/System|/User|/Users|/Volumes|/backups|/bdsm|/bin|/boot|/cores|/data|/dev|/etc|/home|/lib|/lib64|/mach_kernel|/media|/misc|/mnt|/net|/opt|/private|/proc|/root|/sbin|/selinux|/srv|/sys|/tmp|/usr|/var))
      rvm_debug "__rvm_rm_rf target is not valid - can not remove"
      return 1
      ;;
    (*)
      if
        [[ -z "${target}" ]]
      then
        rvm_debug "__rvm_rm_rf target not given"
        return 1
      elif
        [[ -d "${target}" ]]  # directory
      then
        \command \rm -rf "${target}" ||
        {
          \typeset ret=$?
          rvm_debug "__rvm_rm_rf error removing target dir '${target}'."
          return $ret
        }
      elif
        [[ -f "${target}" || -L "${target}" ]] # file / broken symbolic link
      then
        \command \rm -f "${target}" ||
        {
          \typeset ret=$?
          rvm_debug "__rvm_rm_rf error removing target file/link '${target}'."
          return $ret
        }
      else
        rvm_debug "__rvm_rm_rf already gone: $*"
      fi
      ;;
  esac
  true # for OSX
}

# Cleans up temp folders for a given prefix ($1),
# or the current process id.
__rvm_cleanup_tmp()
{
  if
    [[ -d "${rvm_tmp_path}/" ]]
  then
    case "${rvm_tmp_path%\/}" in
      *tmp)
        __rvm_rm_rf "${rvm_tmp_path}/${1:-$$}*"
        ;;
    esac
  fi
  true # for osx
}
